/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package knowledgebase.dao;

import java.sql.SQLException;
import java.util.List;
import knowledgebase.model.Document;
import knowledgebase.model.DocumentBlock;
import org.hibernate.HibernateException;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;

/**
 *
 * @author yzaretskyy
 */
@Repository("documentBlockDAO")
public class DocumentBlockDAOImpl implements DocumentBlockDAO{

    private HibernateTemplate hibernateTemplate;
    
    @Autowired
    public void setSessionFactory(SessionFactory sessionFactory) {
        hibernateTemplate = new HibernateTemplate(sessionFactory);
    }
    
    @Override
    public DocumentBlock getDocumentBlock(String id) {
        return hibernateTemplate.get(DocumentBlock.class, id);
    }

    @Override
    public void saveOrUpdateDocumentBlock(DocumentBlock block) {
        hibernateTemplate.saveOrUpdate(block);
        changeCurrentBlockFlag(block.getId(), block.getInnerId());
    }
    
    @Override
    public void removeDocumentBlockById(String id) {
        DocumentBlock block = getDocumentBlock(id);
        hibernateTemplate.delete(block);
    }

    @Override
    public List<DocumentBlock> getDocumentBlocksByDocumentId(Document document) {
        return (List<DocumentBlock>) hibernateTemplate.find("from DocumentBlock where parentDocument = ? and current = 1", document);
    }
    
    public void changeCurrentBlockFlag(final String documentBlockId, final String newInnerDocumentBlockId) {
        hibernateTemplate.execute(new HibernateCallback() {

            @Override
            public Object doInHibernate(Session sn) throws HibernateException, SQLException {
                SQLQuery sqlQuery = sn.createSQLQuery("CALL SP_CHANGE_CURRENT_BLOCK_FLAG(:documentBlockId, :newInnerDocumentBlockId)");
                sqlQuery.setString("documentBlockId", documentBlockId);
                sqlQuery.setString("newInnerDocumentBlockId", newInnerDocumentBlockId);
                sqlQuery.executeUpdate();
//                Query query = sn.createQuery("update DocumentBlock set current = 0 where current = 1 and id = :id");
//                query.setString("id", documentBlockId);
//                query.executeUpdate();
//                query = sn.createQuery("update DocumentBlock set current = 1 where innerId = :innerId and id = :id");
//                query.setString("id", documentBlockId);
//                query.setString("innerId", documentBlockId);
//                query.executeUpdate();
                return null;
            }
        });
    }
    
}
